package com.shjn.squirrel.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.shjn.squirrel.R;
import com.shjn.squirrel.model.UserInfoCache;
import com.shjn.squirrel.utils.ForbiddenSysKeyBoardUtils;
import com.shjn.squirrel.utils.PhoneCheckUtils;
import com.shjn.squirrel.utils.SoundPlayUtils;
import com.shjn.squirrel.customView.BackAndTimerView;
import com.shjn.squirrel.customView.UserDigitalKeyboard;

/**
 * 用户手机号登录
 */
public class UserTeleFragment extends BaseFragment implements View.OnClickListener {

    private static UserTeleFragment instance;
    private EditText mEditTel;
    private UserDigitalKeyboard mUserDigitalKeyboard;
    private Button mConfirm;
    private TextView mProtocol;
    private TextView mSwitchScan;
    private CheckBox mCheckProto;

    public UserTeleFragment() {
    }

    public synchronized static UserTeleFragment getInstance() {
        if (instance == null) {
            instance = new UserTeleFragment();
        }
        return instance;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return createView(inflater, R.layout.user_tele_login, container);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initTimer();
        initView();
    }

    /**
     * 初始化倒计时器
     */
    private void initTimer() {
        //加载定时器面板，设置定时时间
        mActivity.mBackAndTimer.setOnBackListener(new BackAndTimerView.OnBackListener() {
            @Override
            public void onBack() {
                //返回首页
                if (!UserSelectFragment.getInstance().isAdded()) {
                    mActivity.mBackAndTimer.setVisibleState(false);
                    mActivity.getFragmentManager().beginTransaction()
                            .replace(R.id.mid, UserSelectFragment.getInstance())
                            .commit();
                    TopFragment.getInstance().mBtnMyRecycler.setVisibility(View.VISIBLE);
                }
            }
        }).setBackVisibleState(true).setOnTimerFinishListener(new BackAndTimerView.OnTimerFinishListener() {
            @Override
            public void onTimerFinish() {
                //返回首页
                if (!UserSelectFragment.getInstance().isAdded()) {
                    mActivity.mBackAndTimer.setVisibleState(false);
                    mActivity.getFragmentManager().beginTransaction()
                            .replace(R.id.mid, UserSelectFragment.getInstance())
                            .commit();
                    TopFragment.getInstance().mBtnMyRecycler.setVisibility(View.VISIBLE);
                }
            }
        }).setTime(60).setVisibleState(true).start();
    }

    /**
     * 初始化相关控件
     */
    private void initView() {
        mConfirm = (Button) mView.findViewById(R.id.btn_ok);
        mProtocol = (TextView) mView.findViewById(R.id.tv_protocol);
        mSwitchScan = (TextView) mView.findViewById(R.id.tv_switch_scan);
        mEditTel = (EditText) mView.findViewById(R.id.ed_tel);
        mCheckProto = (CheckBox) mView.findViewById(R.id.check_protocol);

        mConfirm.setOnClickListener(this);
        mProtocol.setOnClickListener(this);
        mSwitchScan.setOnClickListener(this);
        mEditTel.post(new Runnable() {
            @Override
            public void run() {
                mEditTel.getText().clear();
            }
        });
        mEditTel.post(new Runnable() {
            @Override
            public void run() {
                mEditTel.requestFocus();
            }
        });
        mEditTel.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {

            }

            //手机号344显示
            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                if (charSequence == null || charSequence.length() == 0) return;
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < charSequence.length(); i++) {
                    if (i != 3 && i != 8 && charSequence.charAt(i) == ' ') {
                        continue;
                    } else {
                        sb.append(charSequence.charAt(i));
                        if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length() - 1) != ' ') {
                            sb.insert(sb.length() - 1, ' ');
                        }
                    }
                }
                if (!sb.toString().equals(charSequence.toString())) {
                    int index = start + 1;
                    if (sb.charAt(start) == ' ') {
                        if (before == 0) {
                            index++;
                        } else {
                            index--;
                        }
                    } else {
                        if (before == 1) {
                            index--;
                        }
                    }
                    mEditTel.setText(sb.toString());
                    mEditTel.setSelection(index);
                }

            }

            @Override
            public void afterTextChanged(Editable charSequence) {
                if (charSequence.length() < 13) {
                    mConfirm.setEnabled(false);
                    mConfirm.setTextColor(Color.parseColor("#999999"));
                } else {
                    if (mCheckProto.isChecked()) {
                        mConfirm.setEnabled(true);
                        mConfirm.setTextColor(Color.parseColor("#FFFFFF"));
                    }
                }
            }
        });
        //禁止弹出系统键盘，屏蔽长按事件
        ForbiddenSysKeyBoardUtils.bannedSysKeyBoard(mActivity, mEditTel);

        mCheckProto.post(new Runnable() {
            @Override
            public void run() {
                mCheckProto.setChecked(true);
            }
        });
        mCheckProto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked && mEditTel.getText().length() == 13) {
                    mConfirm.setEnabled(true);
                    mConfirm.setTextColor(Color.parseColor("#FFFFFF"));
                } else {
                    mConfirm.setEnabled(false);
                    mConfirm.setTextColor(Color.parseColor("#999999"));
                }
            }
        });
        //键盘初始化
        mUserDigitalKeyboard = (UserDigitalKeyboard) mView.findViewById(R.id.user_digital_keyboard);
        mUserDigitalKeyboard.setEditText(mEditTel);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //切换至扫码开箱页
            case R.id.tv_switch_scan:
                if (!UserScanFragment.getInstance().isAdded()) {
                    mActivity.mBackAndTimer.stop();
                    mActivity.getFragmentManager().beginTransaction()
                            .replace(R.id.mid, UserScanFragment.getInstance())
                            .commit();
                }
                break;
            //展示用户协议
            case R.id.tv_protocol:
                if (!UserProtoDialog.getInstance().isAdded()) {
                    mActivity.mBackAndTimer.stop();
                    UserProtoDialog.getInstance()
                            .setMessage(null)
                            .setOnCloseDialogListener(new BaseDialogFragment.OnCloseDialogListener() {
                                @Override
                                public void onCloseDialog() {
                                    mActivity.mBackAndTimer.setTime(mActivity.mBackAndTimer.getCurrentTime()).start();
                                }
                            })
                            .show(mActivity.getFragmentManager(), "user_protocol");
                }
                break;
            //确认登录
            case R.id.btn_ok:
                if (!UserTelRightDialog.getInstance().isAdded() && !WarningDialog.getInstance().isAdded()) {
                    mActivity.mBackAndTimer.stop();
                    UserInfoCache.telNum = PhoneCheckUtils.getRealTel(mEditTel.getText().toString());
                    if (PhoneCheckUtils.isPhoneLegal(UserInfoCache.telNum)) {
                        //展示手机号确认对话框
                        UserTelRightDialog.getInstance()
                                .setMessage(null)
                                .setOnCloseDialogListener(new BaseDialogFragment.OnCloseDialogListener() {
                                    @Override
                                    public void onCloseDialog() {
                                        mActivity.mBackAndTimer.setTime(mActivity.mBackAndTimer.getCurrentTime()).start();
                                    }
                                })
                                .show(mActivity.getFragmentManager(), "user_tel_right");
                    } else {
                        //展示手机号错误对话框
                        SoundPlayUtils.play(12);
                        WarningDialog.getInstance()
                                .setMessage("请输入正确的手机号")
                                .setOnCloseDialogListener(new BaseDialogFragment.OnCloseDialogListener() {
                                    @Override
                                    public void onCloseDialog() {
                                        mActivity.mBackAndTimer.setTime(mActivity.mBackAndTimer.getCurrentTime()).start();
                                    }
                                })
                                .show(mActivity.getFragmentManager(), "user_tel_error");
                    }
                }
                break;
            default:
                break;
        }
    }
}
